package servlet;

import model.DBUtil;
import model.Puser;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.security.MessageDigest;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@WebServlet("/xiugaimima")
public class xiugaimima  extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        HttpSession session = req.getSession();

        Puser currentUser = (Puser) session.getAttribute("pcurrentUser");
        Integer puid = currentUser.puid;
        String password = req.getParameter("password");
        password = hash(password);
        String newpassword = req.getParameter("newpassword");
        System.out.println(newpassword);
        System.out.println(password);
        PrintWriter out = resp.getWriter();
        try {
            try (Connection c = DBUtil.getConnection()) {
                String sql = "SELECT * FROM puser WHERE puid = ? ORDER BY puid  DESC";
                try (PreparedStatement s = c.prepareStatement(sql)) {
                    s.setInt(1, puid);
                    try (ResultSet rs = s.executeQuery()) {
                        String pass = null;
                        while (rs.next()) {
                           pass = rs.getString("ppassword");
                        }
                        System.out.println(pass);
                        if (password.equals(pass)) {
                            try {
                                // 2. 通过 MySQL 查询，得到用户对象
                                query(puid, newpassword);
                                out.print("<script language='javascript'>alert('Modify the success,Please log in again');window.location.href='/submit';</script>");
                            }catch (SQLException exc) {
                                throw new ServletException(exc);
                            }
                        }
                        else {
                            out.print("<script language='javascript'>alert('Old passworld incorrect');window.location.href='/xiugaimima.html';</script>");
                            return;
                        }
                    }
                }

            }
        } catch (SQLException exception) {
            exception.printStackTrace();
        }

    }
    private Puser query(Integer puid, String password) throws SQLException {
        password = hash(password);
        try (Connection c = DBUtil.getConnection()) {

            String sql = "UPDATE puser SET ppassword = ?WHERE puid =?";
            try (PreparedStatement s = c.prepareStatement(sql)) {
                s.setInt(2, puid);
                s.setString(1, password);
                s.executeUpdate();
            }

        }
        return null;
    }

    private String hash(String ppassword) {
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("SHA-512");

            byte[] bytes = ppassword.getBytes("UTF-8");
            byte[] digest = messageDigest.digest(bytes);
            StringBuilder sb = new StringBuilder();
            for (byte b : digest) {
                sb.append(String.format("%02x", b));
            }
            return sb.toString();

        }  catch (Exception exc) {
            return ppassword;
        }
    }
}


